<template>
  <y-dialog @close="emit('close')" width="1000px" append-to-body>
    <el-form
      ref="associateBugRef"
      :model="form"
      :rules="rules"
      size="default"
      label-width="120px"
    >
      <el-row>
        <el-col>
          <el-form-item label="关联缺陷" prop="associates">
            <el-input
              v-model="form.associates"
              type="textarea"
              :rows="5"
              placeholder="请输入关联缺陷编号，多个值请用英文逗号隔开（,）"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submit">确定</el-button>
        <el-button type="warning" @click="reset">重置</el-button>
        <el-button @click="emit('close')">取消</el-button>
      </div>
    </template>
  </y-dialog>
</template>

<script setup name="BugAssociates">
import { associateBugs } from "@/api/tms/bug";

const { proxy } = getCurrentInstance();

const emit = defineEmits(["submited", "close"]);

const validateNumbers = (rule, value, callback) => {
  // 拆分输入的缺陷编号
  const numbers = value
    .split(",")
    .map((num) => num.trim())
    .filter((num) => num !== "");

  // 检查是否有空值
  if (numbers.length === 0) {
    callback(new Error("请输入至少一个缺陷编号"));
    return;
  }

  // 正则表达式匹配每个缺陷编号
  const pattern = /^[Bb][Uu][Gg]\d{15}$/;

  // 验证每个缺陷编号
  numbers.forEach((num, index) => {
    if (!pattern.test(num)) {
      callback(
        new Error(
          `第 ${
            index + 1
          } 个缺陷编号格式不正确，请输入类似 BUG000000000000000 的格式`
        )
      );
    }
  });
  callback();
};

const data = reactive({
  form: {},
  rules: {
    associates: [
      { required: true, message: "关联缺陷不能为空", trigger: "blur" },
      { validator: validateNumbers, trigger: "blur" },
    ],
  },
});

const { form, rules } = toRefs(data);

const props = defineProps({
  id: { type: String, default: undefined },
});

/** 重置Form方法 */
function reset() {
  form.value = {
    associates: "",
  };
}

/** 提交按钮事件 */
const submit = async () => {
  try {
    await proxy.$refs["associateBugRef"].validate();
    await associateBugs({
      id: props.id,
      associates: splitStringByComma(form.value.associates),
    });
    proxy.$modal.msgSuccess("关联成功");
    submited();
  } catch (error) {
    console.error("关联失败:", error);
  }
};

/** 按英文逗号拆分字符串 */
function splitStringByComma(str) {
  if (str.includes(",")) {
    return str.split(",").map((s) => s.trim());
  } else {
    return [str];
  }
}

/** submited事件 */
function submited() {
  emit("submited");
  emit("close");
}
</script>
